#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: LiuHuan
# Datetime: 2020/9/14 16:28

#"""
#flask_web_4.0
#2020.09.14 新增先导专项分类服务，上海药物所-getCla_shanghai 微藻生物-getCla_weizao
#2020.09.15 create getCla_jingmi
#2020.10.15 先导分类，输出多个标签
#2020.10.25 新增 brain,earth,yintai
#2020.11.25 新增 tu,kongjian,shandi
#2020.12.05 增加POST方法
#2020.12.08 解决post返回乱码问题，get返回多个值问题
#2021.02.24 重要度计算中英文接口规范
#"""


import json

from flask import Flask
from flask import request
from ner import *
from importance.importance_flashweb import compute_importance as compute_importance_en
from classification.classification import getClassification
from bert_base.client import BertClient

app = Flask(__name__)


def compute_importance_cn(text):
    with BertClient(ip='10.0.11.211',port=5575, port_out=5576, show_server_config=False, check_version=False, check_length=False,timeout=100000 ,  mode='CLASS') as bc:
        result = bc.encode([text])
    print(result)
    #if result[0]['pred_label'] == ['0']:
        #result = 1 - result[0]['score'][0]
    #else:
        #result = result[0]['score'][0]
    #print(result)
    return result[0]['score'][0][1]
    # print(result)


with open('id2label_shanghai.json', 'r', encoding='utf-8') as f:
    id2label_shanghai = json.load(f)
    # print(id2label)

def cla_shanghai(text):
    with BertClient(ip='10.0.11.211', port=5573, port_out=5574, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_shanghai[cla]
        cla = str(a.index(s2))
        c2 = id2label_shanghai[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}

    return result_return

with open('id2label_weizao.json', 'r', encoding='utf-8') as f:
    id2label_weizao = json.load(f)
    # print(id2label)

def cla_weizao(text):
    with BertClient(ip='10.0.11.211', port=5571, port_out=5572, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_weizao[cla]
        cla = str(a.index(s2))
        c2 = id2label_weizao[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}

    return result_return

with open('id2label_jingmi.json', 'r', encoding='utf-8') as f:
    id2label_jingmi = json.load(f)
    # print(id2label)

def cla_jingmi(text):
    with BertClient(ip='10.0.11.211', port=5577, port_out=5578, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_jingmi[cla]
        cla = str(a.index(s2))
        c2 = id2label_jingmi[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return

with open('id2label_brain.json', 'r', encoding='utf-8') as f:
    id2label_brain = json.load(f)
    # print(id2label)

def cla_brain(text):
    with BertClient(ip='10.0.11.211', port=5579, port_out=5580, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_brain[cla]
        cla = str(a.index(s2))
        c2 = id2label_brain[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return

with open('id2label_earth.json', 'r', encoding='utf-8') as f:
    id2label_earth = json.load(f)
    # print(id2label)

def cla_earth(text):
    with BertClient(ip='10.0.11.211', port=5581, port_out=5582, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_earth[cla]
        cla = str(a.index(s2))
        c2 = id2label_earth[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return

with open('id2label_yintai.json', 'r', encoding='utf-8') as f:
    id2label_yintai = json.load(f)
    # print(id2label)

def cla_yintai(text):
    with BertClient(ip='10.0.11.211', port=5583, port_out=5584, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_yintai[cla]
        cla = str(a.index(s2))
        c2 = id2label_yintai[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return


with open('id2label_tu.json', 'r', encoding='utf-8') as f:
    id2label_tu = json.load(f)
    # print(id2label)

def cla_tu(text):
    with BertClient(ip='10.0.11.211', port=5585, port_out=5586, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_tu[cla]
        cla = str(a.index(s2))
        c2 = id2label_tu[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return

with open('id2label_shandi.json', 'r', encoding='utf-8') as f:
    id2label_shandi = json.load(f)
    # print(id2label)

def cla_shandi(text):
    with BertClient(ip='10.0.11.211', port=5587, port_out=5588, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_shandi[cla]
        cla = str(a.index(s2))
        c2 = id2label_shandi[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return


with open('id2label_kongjian.json', 'r', encoding='utf-8') as f:
    id2label_kongjian = json.load(f)
    # print(id2label)

def cla_kongjian(text):
    with BertClient(ip='10.0.11.211', port=5589, port_out=5590, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])[0]["score"]
    for a in result:
        a_s = sorted(a,reverse=True)
        s1 = a_s[0]
        s2 = a_s[1]
        cla = str(a.index(s1))
        c1 = id2label_kongjian[cla]
        cla = str(a.index(s2))
        c2 = id2label_kongjian[cla]

    result_return = {"class_1":{"label":c1,"score":s1},"class_2":{"label":c2,"score":s2}}
    return result_return


id2label_funds= {'0':'背景及问题','1':'任务及目标','2':'方法与内容','3':'价值意义'}
def cla_funds(text):
    with BertClient(ip='10.0.11.211', port=5599, port_out=5598, show_server_config=False, check_version=False,
                    check_length=False, timeout=100000, mode='CLASS') as bc:
        result = bc.encode([text])
    result_return = {}
    result_return['label'] = id2label_funds[result[0]['pred_label'][0]]
    result_return['score'] = result[0]['score'][0]

    return result_return

def post_proc(method,data):
    result_return = {"results":[]}
    for text in data:
        result = method(text)
        result_return["results"].append(result["class_1"]["label"])
    return result_return

def get_proc(data):
    return data["class_1"]["label"]


@app.route('/getCla_shanghai', methods=['GET','POST'])
def getCla_shanghai():
    if request.method == 'GET':
        data = cla_shanghai(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_shanghai, data))


@app.route('/getCla_weizao', methods=['GET','POST'])
def getCla_weizao():
    if request.method == 'GET':
        data = cla_weizao(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_weizao, data))

@app.route('/getCla_jingmi', methods=['GET','POST'])
def getCla_jingmi():
    if request.method == 'GET':
        data = cla_jingmi(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_jingmi, data))

@app.route('/getCla_brain', methods=['GET','POST'])
def getCla_brain():
    if request.method == 'GET':
        data = cla_brain(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_brain, data))

@app.route('/getCla_earth', methods=['GET','POST'])
def getCla_earth():
    if request.method == 'GET':
        data = cla_earth(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_earth, data))

@app.route('/getCla_yintai', methods=['GET','POST'])
def getCla_yintai():
    if request.method == 'GET':
        data = cla_yintai(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_yintai, data))

@app.route('/getCla_tu', methods=['GET','POST'])
def getCla_tu():
    if request.method == 'GET':
        data = cla_tu(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_tu, data))

@app.route('/getCla_shandi', methods=['GET','POST'])
def getCla_shandi():
    if request.method == 'GET':
        data = cla_shandi(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_shandi, data))

@app.route('/getCla_kongjian', methods=['GET','POST'])
def getCla_kongjian():
    if request.method == 'GET':
        data = cla_kongjian(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_kongjian, data))


@app.route('/getCla_funds', methods=['GET','POST'])
def getCla_funds():
    if request.method == 'GET':
        data = cla_funds(text=  ' '.join([request.args.get("data").strip()]))
        return str(get_proc(data))
    if request.method == 'POST':
        data =request.form.getlist("data")
        return str(post_proc(cla_funds, data))


@app.route('/getObjectsPost', methods=['POST'])
def getObjectsPost():
    if not request.form["data"]:
        pass
    data = ResultsMerge(text=request.form["data"])
    return str(json.dumps(data))

@app.route('/getObjectsGet', methods=['GET'])
def getObjectsGet():
    if not request.args.get("data"):
        pass
    data = ResultsMerge(text=request.args.get("data"))
    return json.dumps(data)

	
@app.route('/getImportanceCn', methods=['GET'])
def getImportanceCn():
    if not request.args.get("data"):
        pass
    data = compute_importance_cn(text=  ' '.join([request.args.get("data").strip()])) 
    return str(data)

@app.route('/getImportancePostCn', methods=['POST'])
def getImportancePostCn():
    if not request.form["data"]:
        pass 
    data = compute_importance_cn(text=' '.join([request.form["data"].strip()]))
    return str(data)

@app.route('/getImportanceEn', methods=['GET'])
def getImportanceEn():
    if not request.args.get("data"):
        pass
    data = compute_importance_en(text=  ' '.join([request.args.get("data").strip()])) 
    return str(data)

@app.route('/getImportancePostEn', methods=['POST'])
def getImportancePostEn():
    if not request.form["data"]:
        pass 
    data = compute_importance_en(text=' '.join([request.form["data"].strip()]))
    return str(data)

@app.route('/getClassificationGet', methods=['GET'])
def getClassificationGet():
    if not request.args.get("data"):
        pass
    data = getClassification(request.args.get("data"))
    return str(data)

@app.route('/getClassificationPost', methods=['POST'])
def getClassificationPost():
    if not request.form["data"]:
        pass
    data = getClassification(request.form["data"])
    return str(data)

if __name__ == '__main__':
    app.run(host="124.16.154.126", port=8888, debug=True)
    # app.run(port=8888)
